#include <NTPClient.h>
#include <FS.h>
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
# include <TFT_eSPI.h>
#include <WiFiUdp.h>
#include "text.h"
#include "pic.h"
# include <Ticker.h>
Ticker ticker;


// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>
const char *ssid     = "123456789";
const char *password = "WC020118";
const char* host = "api.seniverse.com";     // 将要连接的服务器地址  
const int httpPort = 80;                    // 将要连接的服务器端口
String reqRes = "/v3/weather/now.json?key=S_cQHuKqoxs5MlDn1&location=Zhengzhou&language=zh-Hans&unit=c";

char determineqing[]="晴";
int i=0;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
TFT_eSPI tft = TFT_eSPI(130, 131); //  实例化屏幕，设置屏幕大小
short int weather_symbol;
void setup() {

  tft.init(); //初始化
  tft.fillScreen(TFT_WHITE);
  Serial.begin(115200); //启动串口
   tft.setSwapBytes(true); //显示正确的颜色
  tft.drawLine(0, 30, 130, 30, TFT_BLACK);
  tft.drawLine(0, 90, 130, 90, TFT_BLACK);
  timeClient.setTimeOffset(28800); //设置时间为东八区
  

tft.drawBitmap(90, 10,hz_zhou, 16, 16, TFT_BLACK);

  WiFi.begin(ssid, password); //连接网络
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }
  timeClient.begin(); //启动时间服务
  ticker.attach(0.1,showpeople); //每0.1秒就执行一次。
}

void loop() {

  timeClient.update();
  httpRequest(reqRes);
  Serial.println(timeClient.getFormattedTime());
  unsigned long int epochTime  = timeClient.getEpochTime();
  int hou =  timeClient.getHours() ;
  int minu = timeClient.getMinutes();
  int weekdays = timeClient.getDay();

  struct tm *ptm = gmtime ((time_t *)&epochTime);
  int monthDay = ptm->tm_mday;
  Serial.print("Month day: ");
  Serial.println(monthDay);
  int currentMonth = ptm->tm_mon + 1;
  Serial.print("Month: ");
  Serial.println(currentMonth);
  timeClient.update();//更新时间
  showpage(hou, minu, currentMonth, monthDay, weekdays);
  delay(100);

}
void showpage(int hou, int minu, int mon, int days, int weekdays) {


    
  //显示字体
  // 一个字符的大小几乎是10

  if (hou < 10) {
    showtext(70, 35, 1, 3, TFT_BLACK, TFT_WHITE, "0" + (String)hou + ":\n"); //显示字体
  }
  else showtext(70, 35, 1, 3, TFT_BLACK, TFT_WHITE, (String)hou + ":\n");
  if (minu < 10) {
    showtext(85, 65, 1, 3, TFT_BLACK, TFT_WHITE, "0" + (String)minu);
  }
  else showtext(85, 65, 1, 3, TFT_BLACK, TFT_WHITE, (String)minu); //


  showtext(15, 10, 1, 2, TFT_BLACK, TFT_WHITE, (String)mon + "/" + (String)days);

  shouweekdays(110,10,weekdays);
  Serial.println(weekdays);
  //showHanzi(90,10,hanzi[weekdays+1].Index,TFT_YELLOW);
}
void showtext(int16_t x, int16_t y, uint8_t font, uint8_t s, uint16_t fg, uint16_t bg, const String str)
{
  //设置文本显示坐标，和文本的字体，默认以左上角为参考点，
  tft.setCursor(x, y, font);
  // 设置文本颜色为白色，文本背景黑色
  tft.setTextColor(fg, bg);
  //设置文本大小，文本大小的范围是1-7的整数
  tft.setTextSize(s);
  // 设置显示的文字，注意这里有个换行符 \n 产生的效果
  tft.println(str);
}

void shouweekdays(int32_t x, int32_t y,int i){
  switch (i){
    case 1:{
      tft.drawBitmap(x, y,hz_Mon, 16, 16, TFT_BLACK);
    break;}
        case 2:{
           tft.drawBitmap(x, y,hz_Tue, 16, 16, TFT_BLACK);
    break;}
        case 3:{
           tft.drawBitmap(x, y,hz_Wed, 16, 16, TFT_BLACK);
    break;}
        case 4:{
           tft.drawBitmap(x, y,hz_Thu, 16, 16, TFT_BLACK);
    break;}
        case 5:{
           tft.drawBitmap(x, y,hz_Fri, 16, 16, TFT_BLACK);
    break;}
        case 6:{
           tft.drawBitmap(x, y,hz_Sat, 16, 16, TFT_BLACK);
    break;}
        case 0:{
           tft.drawBitmap(x, y,hz_Sunday, 16, 16, TFT_BLACK);
    break;}
  }}



   void httpRequest(String reqRes ){
    WiFiClient client;
   String answer;
   String httpRequest = String("GET ") + reqRes + " HTTP/1.1\r\n" + 
                              "Host: " + host + "\r\n" + 
                              "Connection: close\r\n\r\n";
    
      // 尝试连接服务器
  if (client.connect(host, 80)){
    Serial.println(" Success!");
 
    // 向服务器发送http请求信息
    client.print(httpRequest);
    delay(100);
  
    
    while(client.available()){
           String line = client.readStringUntil('\r');
            answer = answer +line;
      
      }
    client.stop();
    Serial.println(answer);
    }
    // Stream& input;
  // Stream& input;
 String jsonAnswer;
  int jsonIndex;
  //找到有用的返回数据位置i 返回头不要
  for (int i = 0; i < answer.length(); i++) {
    if (answer[i] == '{') {
      jsonIndex = i;
      break;
    }
  }
  jsonAnswer = answer.substring(jsonIndex);
  
StaticJsonDocument<512> doc;

DeserializationError error = deserializeJson(doc, jsonAnswer);

if (error) {
  Serial.print(F("deserializeJson() failed: "));
  Serial.println(error.f_str());
  return;
}

JsonObject results_0 = doc["results"][0];

JsonObject results_0_location = results_0["location"];
const char* results_0_location_id = results_0_location["id"]; // "WW0V9QP93VS8"
const char* results_0_location_name = results_0_location["name"]; // "郑州"
const char* results_0_location_country = results_0_location["country"]; // "CN"
const char* results_0_location_path = results_0_location["path"]; // "郑州,郑州,河南,中国"
const char* results_0_location_timezone = results_0_location["timezone"]; // "Asia/Shanghai"
const char* results_0_location_timezone_offset = results_0_location["timezone_offset"]; // "+08:00"

JsonObject results_0_now = results_0["now"];
const char* results_0_now_text = results_0_now["text"]; // "晴"
const char* results_0_now_code = results_0_now["code"]; // "0"
const char* results_0_now_temperature = results_0_now["temperature"]; // "14"
const char* results_0_last_update = results_0["last_update"]; // "2021-11-13T09:27:48+08:00"


if(strcmp(results_0_now_text,determineqing)==0){
  tft.drawBitmap(60, 105,qing, 16, 16, TFT_BLACK);
  tft.pushImage(5, 92,  40, 40, sun);//显示晴天图片
  Serial.println("晴");
  }
  else{Serial.println("天气显示失败");
  Serial.println(results_0_now_text);
  if(results_0_now_text == "晴")Serial.println("1");
  }

  
showtext(80,105,1,2, TFT_BLACK, TFT_WHITE, (String)results_0_now_temperature);
showtext(105,100,1,1,TFT_BLACK, TFT_WHITE, ".\n");
showtext(112,108,1,1,TFT_BLACK, TFT_WHITE, "C\n");
    }
void showpeople(){
     tft.pushImage(0, 30,  64, 64, bmp_table_white[i]);//显示晴天图片
    i++;
    if(i>5) i=0;
  }
